package com.jd.dl.util;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AppPathUtil {

	private Log log = LogFactory.getLog(this.getClass());
	
	private static AppPathUtil _instance = null;
	
	private AppPathUtil() {}
	
	public static AppPathUtil getInstance() {
		if (_instance == null) {
			_instance = new AppPathUtil();
		}
		return _instance;
	}
	
	public String getDeployRoot() {
		String path = getTomcatRoot();
		if (path.lastIndexOf(File.separator) > 0) {
			path = path.substring(0,path.lastIndexOf(File.separator));
		}
		if (log.isDebugEnabled()) {
			log.debug("Deploy Root Path: " + path);
		}
		return path;
	}
	
	public String getTomcatRoot() {
		String path = getClassPath();
		if (path.indexOf("/tomcat") > 0) {   
			path = path.substring(0,path.indexOf("/tomcat"));   
		}
		if (log.isDebugEnabled()) {
			log.debug("Tomcat Root Path: " + path);
		}
		return path;
	}
	
	public String getAppRoot() {
		String path = getClassPath();
		if (path.indexOf("WEB-INF") > 0) {   
			path = path.substring(0,path.indexOf("/WEB-INF/classes"));   
		}   
		if (log.isDebugEnabled()) {
			log.debug("App Root Path: " + path);
		}
		return path;
	}
	
	public String getAppTmp() {
		String path = getAppRoot();
		return path + File.separator + "tmp";
	}
	
	public String getClassPath() {
		String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
		return path.substring(1);
	}

}
